/* $RCSFile: ChangePwd.aspx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/Secure2/ChangePwd.aspx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:22  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:44:01  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:26  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;

using AddonNice;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Core;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Authentication;
using AddonNice.Security;
using AddonNice.Settings;
using AddonNice.CRMWrapper;
using AddonNice.Helpers;
using System.Text;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.Secure
{
    public partial class ChangePwd : StaticStdAuxPage
    {
        // Must be const PageChangePwdID
        public override int PageID
		{
			get
			{   return StStr.PageChangePwdID; }
		}

        protected void Page_Load(object sender, EventArgs e)
        {
            if ( PageTraceSwitch.Sw.TraceVerbose )
    		    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ChangePwd Page_Load BEG IsPostBack: {0}",IsPostBack),PageTraceSwitch.Sw.Info);
            if (!Page.IsPostBack)
            {
                // pop the return url
                string str = ReturnUrl;
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RegisterCRM Page_Load ReturnUrl: '{0}'.", str), PageTraceSwitch.Sw.Info);
                // and push again everything to prepare in case somebody call properties for this moduel
                ReturnUrl = str;
                if (!string.IsNullOrEmpty(str))
                {
                    ChangePassword1.ContinueDestinationPageUrl = str;
                    ChangePassword1.CancelDestinationPageUrl = str;
                }
            }
        }

        protected override void OnPreInit(EventArgs e)
        {
            MasterPage m                =   Master; // to instanciate controls
            string strcult              =   LocalizeHelper.GetCurrentNeutralCultureName();
            if ( ChangePassword1.ChangePasswordTemplateContainer != null )
            {
                Control ctl =   ChangePassword1.ChangePasswordTemplateContainer.FindControl("BtnChangePassword");
                if ( ctl != null && ( ctl is ImageButton ) )
                {
                    ctl.SkinID  =   "Validate_" + strcult;
                    ((ImageButton)ctl).CommandName  =   ChangePassword.ChangePasswordButtonCommandName;
                }
                
                ctl =   ChangePassword1.ChangePasswordTemplateContainer.FindControl("CancelBtn");
                if ( ctl != null && ( ctl is ImageButton ) )
                {
                    ctl.SkinID  =   "Cancel_" + strcult;
                    ((ImageButton)ctl).CommandName  =   ChangePassword.CancelButtonCommandName;
                }
                ctl =   ChangePassword1.ChangePasswordTemplateContainer.FindControl("EditProfileLink");
                if ( ctl != null && ( ctl is HyperLink ) )
                {
                    ((HyperLink)ctl).NavigateUrl    =   HttpUrlBuilder.BuildUrl("~/editprofile.aspx",true,DynPageLoc.Secured,StStr.PageEditProfileID);
                }
            }

            if ( ChangePassword1.SuccessTemplateContainer != null )
            {
                Control ctl =   ChangePassword1.SuccessTemplateContainer.FindControl("BtnContinue");
                if ( ctl != null && ( ctl is ImageButton ) )
                {
                    ctl.SkinID  =   "Continue_" + strcult;
                    ((ImageButton)ctl).CommandName  =   ChangePassword.ContinueButtonCommandName;
                }
                ctl =   ChangePassword1.SuccessTemplateContainer.FindControl("BtnHome");
                if ( ctl != null && ( ctl is ImageButton ) )
                {
                    ctl.SkinID  =   "Finish_" + strcult;
                    ((ImageButton)ctl).Click +=new ImageClickEventHandler(BtnHome_Click);
                }
                ctl =   ChangePassword1.SuccessTemplateContainer.FindControl("EditProfileLinkSuccess");
                if ( ctl != null && ( ctl is HyperLink ) )
                {
                    ((HyperLink)ctl).NavigateUrl    =   HttpUrlBuilder.BuildUrl("~/editprofile.aspx",true,DynPageLoc.Secured,StStr.PageEditProfileID);
                }
            }
            
            base.OnPreInit(e);
        }

        void BtnHome_Click(object sender, ImageClickEventArgs e)
        {
            PortalSecurity.PortalHome(true,this);
        }

        protected override void OnInit(EventArgs e)
        {
            if ( PageTraceSwitch.Sw.TraceVerbose )
    		    Trace2.WriteLine("[V]ChangePwd OnInit BEG.",PageTraceSwitch.Sw.Info);
            InitializeComponent();
            base.OnInit(e);
            if ( PageTraceSwitch.Sw.TraceVerbose )
    		    Trace2.WriteLine("[V]ChangePwd OnInit END.",PageTraceSwitch.Sw.Info);
        }
        
        MembershipValidatePasswordEventHandler EvPwd    =   null;
        string newPwd                                   =   string.Empty;

        private void InitializeComponent()
        {
            Load                                    +=  new EventHandler(Page_Load);
            ChangePassword1.SendingMail             +=  new MailMessageEventHandler(ChangePassword1_SendingMail);
            ChangePassword1.MembershipProvider      =   "AddonNiceMembershipProvider";
            // This is to try getting the new pwd because renewpassword don't give access to it before ceating mail body with default values
            EvPwd    =   new MembershipValidatePasswordEventHandler(Provider_ValidatingPassword);
            Membership.Provider.ValidatingPassword  +=  EvPwd;
            // We need to set something here, else MailDefinition will go in the smtp config to get default From email and throw an exception if not there....
            ChangePassword1.MailDefinition.From     =   Config.EmailFrom;
            ChangePassword1.MailDefinition.Subject  =   LocalizeHelper.Localize("LOGIN_CHANGE_SUBJECT", "Your password has been changed");
            ChangePassword1.EditProfileUrl          =   HttpUrlBuilder.BuildUrl("~/editprofile.aspx",true,DynPageLoc.Secured,StStr.PageEditProfileID);
        }

        // we must take care to free provider from the Validationg pwd event
        protected override void OnUnload(EventArgs e)
        {
            if ( EvPwd != null )
                Membership.Provider.ValidatingPassword -= EvPwd;
            base.OnUnload(e);
        }

        void Provider_ValidatingPassword(object sender, ValidatePasswordEventArgs e)
        {
            bool Ok =   (e.UserName == ChangePassword1.UserName);
            if ( SecurityTraceSwitch.Sw.TraceVerbose )
    		    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ChangePwd Provider_ValidatingPassword BEG UserName: {0}, internalUserName: {1}, Ok: {2}",
                    e.UserName,ChangePassword1.UserName,Ok),SecurityTraceSwitch.Sw.Info);
            if ( Ok )
                newPwd   =   e.Password;
        }

        // Send mail by crm 
        void ChangePassword1_SendingMail(object sender, MailMessageEventArgs e)
        {
            if ( SecurityTraceSwitch.Sw.TraceVerbose )
    		    Trace2.WriteLine("[V]ChangePwd ChangePassword1_SendingMail BEG.",SecurityTraceSwitch.Sw.Info);
            try
            {
                string subj                 =   LocalizeHelper.Localize("LOGIN_CHANGE_SUBJECT", "Your Password has been changed");
                ADNDynEmail cmail            =   new ADNDynEmail(Wrapper, subj);
                cmail.SetOwnerFromUserId();
                AddonNiceMembershipUser user = (AddonNiceMembershipUser)Membership.GetUser(true);
                if (string.IsNullOrEmpty(newPwd))
                    cmail.description       =   e.Message.Body;
                else
                {
                    StringBuilder sb        =   new StringBuilder();
                    string str              =   LocalizeHelper.Localize("LOGIN_CHANGE_BODY_HELLO", "Hello {0},");
                    if ( !string.IsNullOrEmpty(user.nickname) )
                         sb.AppendFormat(str, user.nickname);
                    else sb.AppendFormat(str, user.UserName);
                    sb.AppendLine();
                    str     =   LocalizeHelper.Localize("LOGIN_CHANGE_BODY_PWDGEN", "Your password has been for a new value.");
                    sb.AppendLine(str);
                    sb.AppendLine();
                    str     =   LocalizeHelper.Localize("LOGIN_CHANGE_BODY_SIGNATURE", "Your system administrator.");
                    cmail.description       =   Server.HtmlEncode(sb.ToString());
                }
                
                cmail.AddDest(user.CustomerId.GetDynUser(Wrapper,ResetWrapper),user.CrmEMail);
                
                ADNDynSystemUser DynSender   =   user.GetImpersonateUser(Wrapper);
                cmail.AddSender(DynSender, DynSender.internalemailaddress);
                
                cmail.directioncode         =   true;
                cmail.mimetype              =   "text/html";
                cmail.sender                =   user.CrmEMail;
                if ( SecurityTraceSwitch.Sw.TraceVerbose )
    		        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ChangePwd ChangePassword1_SendingMail user.mail: {0}, sender.mail: {1}.",user.CrmEMail,DynSender.internalemailaddress),SecurityTraceSwitch.Sw.Info);
                cmail.adminCreate();
                cmail.Send(true);
                e.Cancel                    =   true;// we don't cancel if crm fails: let a chance for this server to sent a reduced version
                if ( SecurityTraceSwitch.Sw.TraceVerbose )
    		        Trace2.WriteLine("[V]ChangePwd ChangePassword1_SendingMail END.",SecurityTraceSwitch.Sw.Info);
            }
            catch (Exception ex1)
            {
                if (SecurityTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]RegisterCRM ChangePassword1_SendingMail ex: {0}", ex1),SecurityTraceSwitch.Sw.Info);
                throw;
            }
        }
    }
}
